package com.qiyadeng.wechat.roo.web;
import com.qiyadeng.wechat.config.WeChatConstant;
import com.qiyadeng.wechat.roo.model.Article;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@RequestMapping("/articles")
@Controller
@RooWebScaffold(path = "articles", formBackingObject = Article.class)
public class ArticleController {

	@RequestMapping(value = "/{articleId}", produces = "text/html")
    public String show(@PathVariable("articleId") Integer articleId, Model uiModel) {
        addDateTimeFormatPatterns(uiModel);
        Article a = Article.findArticle(articleId);
        uiModel.addAttribute("article", a);
        uiModel.addAttribute("itemId", articleId);
        return "articles/show";
    }

	@RequestMapping(method = RequestMethod.POST, produces = "text/html")
    public String create(@Valid Article article, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, article);
            return "articles/create";
        }
        uiModel.asMap().clear();
        article.persist();
        article.setArticleUrl(WeChatConstant.BASE_PIC_WEBSITE+"/wechat/article?id="+article.getArticleId());
        article.merge();
        return "redirect:/articles/" + encodeUrlPathSegment(article.getArticleId().toString(), httpServletRequest);
    }
}
